//
//  EditViewController.m
//  BluetoothBalloonHangingBasket
//
//  Created by FENGYL on 2016/12/8.
//  Copyright © 2016年 FENGYL. All rights reserved.
//

#import "EditViewController.h"
#import "UIView+XL.h"
#import<AssetsLibrary/AssetsLibrary.h>

static NSString * scrollViewIndex = @"ScrollViewIndex";
static NSString * welcomeImage = @"WelcomeImage";

@interface EditViewController ()<UIScrollViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *imageScrollView;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
@property (weak, nonatomic) IBOutlet UIButton *selectPicButton;
@property (weak, nonatomic) IBOutlet UIButton *saveButton;

@property (strong , nonatomic) NSMutableArray * imageArray;

@property (strong , nonatomic) UIImageView * previousImageView;
@property (strong , nonatomic) UIImageView * currentImageView;
@property (strong , nonatomic) UIImageView * nextImageView;

@property (assign , nonatomic) int index;
@property (assign , nonatomic) BOOL isFirst;
@property (strong , nonatomic) UIImage * backgroundImage;
@property (strong , nonatomic) UIImageView * pickerImageView;

@end

@implementation EditViewController

-(NSMutableArray *)imageArray{
    
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
        for (int i = 1; i < 8; i++) {
            
            NSString * string = [NSString stringWithFormat:@"wp_0%d",i];
            
            [_imageArray addObject:string];
            
        }
    }
    return _imageArray;
}

-(UIImageView *)pickerImageView{
    if (!_pickerImageView) {
        _pickerImageView = [[UIImageView alloc]initWithFrame:_imageScrollView.frame];
    }
    return _pickerImageView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isFirst = YES;
    
    //按钮
    self.selectPicButton.layer.cornerRadius = 15;
    self.saveButton.layer.cornerRadius = 15;
    
}

-(void)viewDidAppear:(BOOL)animated{
    
    if (self.isFirst) {
        
        [self setUpIndex];
        
        [self setUpImageScrollView];
        
        self.isFirst = NO;
        
    }
    
}

-(void)setUpIndex{
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString * string = [userDefaults valueForKey:scrollViewIndex];
    
    if (string == nil) {
        
        self.index = 0;
        
    }else{
        
        self.index = [string intValue];
        
    }
    
}


#pragma mark 设置scrollview
-(void)setUpImageScrollView{
    
    self.imageScrollView.bounces = NO;
    
    self.imageScrollView.delegate = self;
    
    //分页
    self.imageScrollView.pagingEnabled = YES;
    
    //隐藏滚动条
    [self.imageScrollView setShowsVerticalScrollIndicator:NO];
    [self.imageScrollView setShowsHorizontalScrollIndicator:NO];
    
    //设置页数
    self.pageControl.numberOfPages = self.imageArray.count;
    self.pageControl.currentPage = self.index;
    self.pageControl.userInteractionEnabled = NO;
    
    NSLog(@"1 %f",self.imageScrollView.width);
    
    //获取scrollview长宽
    CGFloat width = self.imageScrollView.width;
    CGFloat height = self.imageScrollView.height;
    
    //设置scrollview可滑动范围
    [self.imageScrollView setContentSize:CGSizeMake(width * 3, height)];
    
    //移动到当前页
    self.imageScrollView.contentOffset = CGPointMake(width, 0);
    
    
    self.previousImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, width, height)];
    self.currentImageView = [[UIImageView alloc]initWithFrame:CGRectMake(width + 0, 0, width, height)];
    self.nextImageView = [[UIImageView alloc]initWithFrame:CGRectMake(width * 2, 0, width, height)];
    
    [self.previousImageView setImage:[UIImage imageNamed:self.imageArray[[self getArrayIndex:NO]]]];
    [self.currentImageView setImage:[UIImage imageNamed:self.imageArray[self.index]]];
    [self.nextImageView setImage:[UIImage imageNamed:self.imageArray[[self getArrayIndex:YES]]]];
    
    [self.imageScrollView addSubview:self.previousImageView];
    [self.imageScrollView addSubview:self.currentImageView];
    [self.imageScrollView addSubview:self.nextImageView];
    
    NSLog(@"scroll %f image %f",self.imageScrollView.width,self.previousImageView.width);
    
}


#pragma mark 滑动完成之后复位
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (scrollView.contentOffset.x < scrollView.width) {
        
        int i = [self getArrayIndex:NO];
        
        [self.nextImageView setImage:[UIImage imageNamed:self.imageArray[self.index]]];
        
        [self.currentImageView setImage:[UIImage imageNamed:self.imageArray[i]]];
        
        self.index = i;
        
        i = [self getArrayIndex:NO];
        
        [self.previousImageView setImage:[UIImage imageNamed:self.imageArray[i]]];

        self.imageScrollView.contentOffset = CGPointMake(scrollView.width, 0);
        
        self.pageControl.currentPage = self.index;
        
        NSLog(@"2 %f",self.imageScrollView.width);
        
        NSLog(@"previous");
        
    }else if (scrollView.contentOffset.x > scrollView.width){
        
        int i = [self getArrayIndex:YES];
        
        [self.previousImageView setImage:[UIImage imageNamed:self.imageArray[self.index]]];
        
        [self.currentImageView setImage:[UIImage imageNamed:self.imageArray[i]]];
        
        self.index = i;
        
        i = [self getArrayIndex:YES];
        
        [self.nextImageView setImage:[UIImage imageNamed:self.imageArray[i]]];
        
        self.imageScrollView.contentOffset = CGPointMake(scrollView.width, 0);
        
        self.pageControl.currentPage = self.index;
        
        NSLog(@"next");
        
    }
    
}

-(int)getArrayIndex:(BOOL)isNext{
    
    int i = 0;
    
    if (isNext) {
        
        if (self.index == 6) {
            
            i = 0;
            
        }else{
            
            i = self.index + 1;
            
        }
        
    }else{
        
        if (self.index == 0) {
            
            i = 6;
            
        }else{
            
            i = self.index - 1;
            
        }
        
    }
    
    return i;
    
}

#pragma mark 保存壁纸
- (IBAction)saveWallpaper:(id)sender {
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    [userDefaults setValue:[NSString stringWithFormat:@"%d",self.index] forKey:scrollViewIndex];
    
    UIImage * image;
    
    //获取document路径
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    //拼接路径
    NSString *filePath = [path stringByAppendingPathComponent:welcomeImage];
    
    if (_pickerImageView) {
        
        //通过归档的方式存储
        [NSKeyedArchiver archiveRootObject:_pickerImageView.image toFile:filePath];
        
        image = _pickerImageView.image;
        
    }else{
        
        //通过归档的方式存储
        [NSKeyedArchiver archiveRootObject:self.currentImageView.image toFile:filePath];
        
        image = self.currentImageView.image;
        
    }
    
    
    [self.navigationController.viewControllers objectAtIndex:(self.navigationController.viewControllers.count) - 2].view.layer.contents = (id)image.CGImage;
    
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark 选择图片
- (IBAction)selectPic:(id)sender {
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = NO;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
//    ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];
//    
//    if (status == ALAuthorizationStatusRestricted || status == ALAuthorizationStatusDenied){
//        //无权限 引导去开启
//        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
//        if ([[UIApplication sharedApplication] canOpenURL:url]) {
//            [[UIApplication sharedApplication] openURL:url];
//        }
//        
//    }else{
//        
//        [self.navigationController presentViewController:imagePickerController animated:YES completion:nil];
//        
//    }
    
    [self.navigationController presentViewController:imagePickerController animated:YES completion:nil];
    
    
    
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    self.backgroundImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    if (_pickerImageView) {
        
        [self.pickerImageView setImage:self.backgroundImage];
        
    }else{
        
        [self.pickerImageView setImage:self.backgroundImage];
        
        self.imageScrollView.alpha = 0;
        
        [self.view addSubview:self.pickerImageView];
        
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
